<template>
  <div id="personalInfoPage">
    <h2 style="margin-bottom: 16px">个人信息设置</h2>
    <a-card>
      <a-form
        name="personalForm"
        layout="vertical"
        :model="formState"
        @finish="handleSubmit"
      >
        <a-form-item name="userAccount" label="账号">
          <a-input
            v-model:value="formState.userAccount"
            disabled
            placeholder="用户账号"
          />
        </a-form-item>
        <a-form-item name="userName" label="用户名" :rules="[{ required: true, message: '请输入用户名' }]">
          <a-input
            v-model:value="formState.userName"
            placeholder="请输入用户名"
            allow-clear
          />
        </a-form-item>

        <!-- 头像上传区域 -->
        <a-form-item name="userAvatar" label="头像">
          <a-upload
            list-type="picture-card"
            :show-upload-list="false"
            :custom-request="handleAvatarUpload"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="formState.userAvatar" :src="formState.userAvatar" alt="avatar" />
            <div v-else>
              <loading-outlined v-if="uploadLoading"></loading-outlined>
              <plus-outlined v-else></plus-outlined>
              <div class="ant-upload-text">上传头像</div>
            </div>
          </a-upload>
        </a-form-item>

        <a-form-item name="userProfile" label="个人简介">
          <a-textarea
            v-model:value="formState.userProfile"
            placeholder="请输入个人简介"
            :auto-size="{ minRows: 3, maxRows: 6 }"
            allow-clear
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit" :loading="loading">
            保存修改
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue'
import type { UploadProps } from 'ant-design-vue'
import { updateUserSelfUsingPost } from '@/api/userController.ts'
import { uploadAvatarUsingPost } from '@/api/fileController.ts' // 导入头像上传接口
import { message } from 'ant-design-vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { getCosFullUrl, getCosRelativePath } from '@/constants/cos.ts'
const router = useRouter()
const loginUserStore = useLoginUserStore()
const loading = ref(false)
const uploadLoading = ref(false) // 头像上传加载状态

// 表单状态
const formState = reactive<API.User>({
  userAccount: '',
  userName: '',
  userAvatar: '',
  userProfile: ''
})

// 初始化表单数据
const initForm = () => {
  const userInfo = loginUserStore.loginUser
  if (userInfo) {
    formState.userAccount = userInfo.userAccount || ''
    formState.userName = userInfo.userName || ''

    // 添加对象存储前缀，确保完整的URL
    if (userInfo.userAvatar) {
      formState.userAvatar = getCosFullUrl(userInfo.userAvatar)
    } else {
      formState.userAvatar = userInfo.userAvatar || ''
    }
    formState.userProfile = userInfo.userProfile || ''
  }
}

// 头像上传前校验
const beforeAvatarUpload = (file: UploadProps['fileList'][number]) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('仅支持JPG/PNG格式的图片')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('头像大小不能超过2MB')
    return false
  }
  return true
}


// 处理头像上传
const handleAvatarUpload = async ({ file }: any) => {
  uploadLoading.value = true
  try {
    // 使用专门的头像上传接口
    const res = await uploadAvatarUsingPost({}, file)

    // 根据BaseResponseString_类型和对象存储特性修改返回数据处理
    let avatarUrl = ''
    if (res.code === 0 && res.data) {
      message.success('头像上传成功')
      avatarUrl = res.data
    } else if (res.data && res.data.code === 0 && res.data.data) {
      // 兼容原来的嵌套结构
      message.success('头像上传成功')
      avatarUrl = res.data.data
    } else {
      message.error('上传失败：' + (res.message || res.data?.message || '未知错误'))
      uploadLoading.value = false
      return
    }

    // 添加对象存储前缀，确保完整的URL
    formState.userAvatar = getCosFullUrl(avatarUrl)
  } catch (error: any) {
    message.error('上传失败：' + error.message)
    console.error('头像上传错误', error)
  } finally {
    uploadLoading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  loading.value = true
  try {
    // 保存当前的完整头像URL，用于更新后恢复
    const currentAvatarUrl = formState.userAvatar

    // 构建更新数据，对于头像字段，我们需要提供相对路径给后端
    const updateData = {
      ...formState,
      userAvatar: getCosRelativePath(currentAvatarUrl), // 提供相对路径给后端
      id: loginUserStore.loginUser?.id // 补充用户ID，后端可能需要此参数进行身份验证
    }


    const res = await updateUserSelfUsingPost(updateData)
    if (res.data.code === 0) {
      message.success('个人信息更新成功')
      // 更新全局登录用户信息
      await loginUserStore.fetchLoginUser()

      // 恢复完整的头像URL，确保显示正确
      setTimeout(() => {
        formState.userAvatar = currentAvatarUrl
      }, 100)
    } else {
      message.error('更新失败：' + res.data.message)
    }
  } catch (error: any) {
    message.error('更新失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 页面加载时检查登录状态并初始化表单
onMounted(() => {
  if (!loginUserStore.loginUser?.id) {
    message.warning('请先登录')
    router.push('/user/login')
    return
  }
  initForm()
})
</script>

<style scoped>
#personalInfoPage {
  max-width: 720px;
  margin: 0 auto;
  padding: 24px;
}

/* 头像上传样式 */
:deep(.ant-upload-select-picture-card) {
  width: 120px;
  height: 120px;
}

:deep(.ant-upload img) {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}
</style>
